package com.example.demo.controller;

import com.example.demo.mapper.CustomerRepository;
import com.example.demo.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class CustomerController {
    @Autowired
    CustomerRepository customerRepository;

    @GetMapping("/save")
    public Customer save(@RequestBody Customer customer) {
        customerRepository.save(customer);
        return customer;
    }

    @GetMapping("/customer/{id}")
    public Optional<Customer> getCustomer(@PathVariable("id") Long id) {
        Optional<Customer> customer = customerRepository.findById(id);
        return customer;
    }

    @GetMapping("/list")
    public List<Customer> list() {
        return customerRepository.findAll();
    }

    @GetMapping("/page")
    public List<Customer> page() {
        PageRequest pageRequest = PageRequest.of(0, 3, Sort.Direction.DESC, "id");
        Page<Customer> page = customerRepository.findByName3("san", pageRequest);
        System.out.println(page.getTotalElements());
        System.out.println(page.getTotalPages());
        //按照当前页数、分页大小，查出的分页结果集合
        for (Customer customer : page.getContent()) {
            System.out.println(customer.toString());
        }
        return page.getContent();
    }

}
